#include "Usart.h"



using namespace std;

Usart::Usart() throw (string)
{
        if((fd = open(PORT_ID, O_RDWR)) < 0)
                throw string("Brak urządzenia /dev/ttyUSB0");
        SetCom();
}

Usart::~Usart()
{
        close(fd);
}

void Usart::SetCom() throw (string)
{
        struct termios t;

        if(tcgetattr (fd, &t) < 0) throw string("nie udalo sie pobrac parametrow terminala");
        t.c_iflag = IGNBRK | IGNPAR;
        t.c_oflag = t.c_lflag = t.c_line = 0;
        t.c_cflag = CS8 | CREAD |  CLOCAL | HUPCL | USER_BAUD_RATE;


        /*.......... Ustawienie trybu pracy .........................*/

        /*
         * Ustawione parametry transmisji:  9600 N 1
         *    predkosc             -  9600
         *    kontrola parzystosci -  brak
         *    bity stopu           -  1 bit stopu
         */

        if(tcsetattr (fd, TCSAFLUSH, &t) < 0) throw string("nie udalo sie ustawic parametrow terminala");

        Usart_fd = fd;
}

string Usart::Read(void) throw (string)
{
        char buf[100];
        read(Usart_fd, buf, 100);
        string str(buf);
        return str;
}

void Usart::Write(string str) throw (string)
{
        write(Usart_fd, str.c_str(), str.length());
}



void Usart::WriteByte(unsigned char b) throw (string)
{

        if(write(Usart_fd,&b,1) < 0) throw string("blad zapisu");

}

unsigned char Usart::ReadByte(void) throw (string)
{
        unsigned char b;
        if(read(Usart_fd, &b, 1) < 0) throw string("blad odczytu");

        return b;
}

